<template>
    <el-menu mode="horizontal" router class="header-menu">
        <el-menu-item index="/">
            <el-icon><HomeFilled /></el-icon>
            首页
        </el-menu-item>
        
        <!-- 购物车图标 -->
        <el-menu-item index="/cart" class="float-right">
            <el-badge :value="cartCount" :hidden="cartCount === 0">
                <el-icon><ShoppingCart /></el-icon>
            </el-badge>
            购物车
        </el-menu-item>

        <!-- 未登录显示 -->
        <template v-if="!isLoggedIn">
            <el-menu-item index="/login" class="float-right">
                <el-icon><User /></el-icon>
                登录
            </el-menu-item>
            <el-menu-item index="/register" class="float-right">注册</el-menu-item>
        </template>
        
        <!-- 已登录显示 -->
        <template v-else>
            <el-sub-menu index="user" class="float-right">
                <template #title>
                    <el-icon><User /></el-icon>
                    {{ userInfo?.username || '个人中心' }}
                </template>
                <el-menu-item index="/profile">个人中心</el-menu-item>
                <el-menu-item index="/products/manage">商品管理</el-menu-item>
                <el-menu-item @click="handleLogout">退出登录</el-menu-item>
            </el-sub-menu>
        </template>
    </el-menu>
</template>

<script>
import { computed, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export default {
    name: 'HeaderComponent',
    setup() {
        const store = useStore()
        const router = useRouter()
        const cartCount = ref(0)

        const isLoggedIn = computed(() => store.getters['user/isLoggedIn'])
        const userInfo = computed(() => store.getters['user/userInfo'])

        const updateCartCount = () => {
            const cart = JSON.parse(localStorage.getItem('cart') || '[]')
            cartCount.value = cart.reduce((total, item) => total + item.quantity, 0)
        }

        const handleLogout = async () => {
            try {
                await store.dispatch('user/logout')
                ElMessage.success('退出成功')
                router.push('/login')
            } catch (error) {
                ElMessage.error('退出失败')
            }
        }

        // 监听 localStorage 的变化
        window.addEventListener('storage', updateCartCount)
        
        // 组件挂载时更新购物车数量
        onMounted(() => {
            updateCartCount()
            // 每秒检查一次购物车数量（因为 localStorage 事件只在不同标签页之间触发��
            setInterval(updateCartCount, 1000)
        })

        return {
            isLoggedIn,
            userInfo,
            handleLogout,
            cartCount
        }
    }
}
</script>

<style scoped>
.header-menu {
    padding: 0 20px;
}

.float-right {
    float: right;
}

.el-icon {
    margin-right: 5px;
    vertical-align: middle;
}
</style>
